# -*- coding: utf-8 -*-
import json,os
from jinja2 import Markup
from flask import flash, url_for, redirect, request, current_app
from flask_admin.base import expose
from flask_admin.model.template import EndpointLinkRowAction, LinkRowAction
from flask_wtf import FlaskForm
from sqlalchemy import func
from wtforms import SelectMultipleField, ValidationError
from wtforms.validators import DataRequired
from flask_admin.actions import action
from flask_admin.helpers import (get_form_data, validate_form_on_submit,get_redirect_target, flash_errors)
from flask_admin.contrib.sqla import form, filters as sqla_filters, tools
from . import MyModelView
from . import AjaxQueryIndexLike
from adminApp.extensions import db, redis_store
from adminApp.models.machine import Machine


class TaskLogView(MyModelView):
    fast_mass_delete = False
    # can_create = True
    # can_delete = False
    # can_edit = True
    column_filters = ('machine.idc.name', 'machine.hostname', 'machine.man_mark', 'is_sytem_build', 'command_text', 'command_type', 'run_state', 'result', 'created', 'updated')
    column_list = ('machine.idc.name', 'machine.hostname', 'machine.man_mark', 'is_sytem_build', 'command_type', 'run_state', 'command_text', 'created', 'updated')
    # column_sortable_list = (
    #     'id', 'name', 'category.name', 'author.name', 'serial_state', 'words', 'last_updated', 'created')
    column_labels = {
        'machine':'设备',
        'machine.idc.name': '机房',
        'machine.hostname': '主机名称',
        'machine.man_mark': '自定标识',
        'is_sytem_build':'系统生成',
        'command_text': '任务内容',
        'command_type': '任务类型',
        'run_state': '执行状态',
        'system_uuid': '系统ID',
        'result': '执行结果',
        'created': '创建日期',
        'updated': '更新日期',
    }

    column_formatters = dict(
        command_text=lambda v, c, m, p: m.command_text[:20] if m.command_text else '',
        # result=lambda v, c, m, p:  json.dumps(json.loads(m.result), indent=1) if m.result else '',
        created=lambda v, c, m, p: m.created.strftime("%Y-%m-%d %H:%M:%S"),
        updated=lambda v, c, m, p: m.updated.strftime("%Y-%m-%d %H:%M:%S") if m.updated else ''
    )
    form_excluded_columns = ('created', 'updated', 'is_sytem_build')
    form_ajax_refs = {
        'machine':{
            'fields': ('id', 'hostname', 'man_mark', 'aqy_device_id','system_uuid'),
            'placeholder': '选择设备，查询参数：主机名称，自定标识，爱奇艺ID，系统ID，记录ID',
            'page_size': 10,
            'minimum_input_length': 0,
        }
    }

    def after_model_change(self, form, model, is_created):
        with open('test.sh', 'wb') as f:
            # for i in model.command_text:
            #     print(i,'-',ord(i),'-')
            # a = model.command_text.replace(chr(13)+chr(10), chr(10))
            # print('----------------------------------------------------------')
            # for i in a:
            #     print(i,'-',ord(i),'-')
            f.write(model.command_text.replace(chr(13)+chr(10), chr(10)).encode())
            # f.write(model.command_text.replace(r'\r', r'\n'))
            # f.write("aaaaaaaaaaaaaaaaaaaa1\n")
            # f.write("aaaaaaaaaaaaaaaaaaaa2\n")
            # f.write("aaaaaaaaaaaaaaaaaaaa3\n")
            # f.write("aaaaaaaaaaaaaaaaaaaa4\n")
            # f.write("aaaaaaaaaaaaaaaaaaaa5\n")
            # f.write("aaaaaaaaaaaaaaaaaaaa6\n")

        if model.machine_id:
            # 加入任务队列
            sid = db.session.query(Machine.system_uuid).filter(Machine.id==model.machine_id).scalar()
            if sid:
                redis_store.rpush(current_app.config.get('RD_WILL_TASK_ID'), sid)